/**
 * 表单展示页（填写）
 */
mini.parse();

var arr_child = [];//存放保存子表数据
var arr_main = {   //存放格式化的保存数据
    "cTableName": "",
    "obj" : {}
};

var arr_table = [];//生成表格组件数组
var arr_tab_table = [];//生成tab表格组件数组
var arr_tab = [];
var datepick_main = [];
var datepick_child = [];
var save_data = [];
var tableAll = [];//所有表格的数组，用于删除后清空表格

var arr_cMath_main = [];//所有主表公式
var arr_cMath_child = [];//所有子表公式

var currentCell; //当前点击的单元格field,用于公式
var formRefData = [];//设置参照
var formId;
var action;
var formCode;
var formSh;
var menuId;
var menusFormTypes;
var treeSelected;//树形选中的数据
var textField;//树形字段名
var textFieldValue;//树形字段名对应值
var refField;//树形参照对应的组件name
var complex_add_field;//树形参照保存时新增的字段
var complex_add_value;//树形参照保存时新增的字段值
var reSelectFlag = false;//树形参照带过来的字段是否重选
var component_data;
var edit_data;
var edit_form = [];//编辑的表单数据
var edit_table = [];//编辑的表格数据

var formItem = parent.getFormItem();//菜单跳转后获取数据

var cFormName; //表单名称
formInit();

//初始化表单
function formInit(){
	
    formSh = localStorage.getItem("formShow");
    userInfo = localStorage.getItem("item");
    console.log(formItem,'formItem');
    console.log(userInfo,'userInfo');
    
//    if(formSh.menusFormTypes == "form") {
    if(formSh == undefined) {//菜单跳转，add
        formId = formItem.item.formListId;
        menuId = formItem.item.id.match(/menuId(\S*)/)[1];
        action = 'add';

        mini.get("add").enable();
        mini.get("edit").disable();
        mini.get("save").disable();
        mini.get("remove").disable();
        mini.get("cancel").disable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").disable();
        mask();
    }else {//按钮跳转，add/edit
    	formSh = $.parseJSON(formSh);
        menuId = formSh.menuId;
        console.log(formSh,'formShow');
        action = formSh.action;
        formId = formSh.formListId;
        menusFormTypes = formSh.menusFormTypes;

        if(menusFormTypes == 'complex') {
            treeSelected = formSh.treeSelected;//档案需要赋值的数据
            textField = formSh.textField;
            textFieldValue = treeSelected[textField];
            complex_add_field = formSh.complex_add_field;
            complex_add_value = treeSelected.id;
            console.log(textFieldValue,'textFieldValue');
        }
        mini.get("add").disable();
        mini.get("edit").disable();
        mini.get("save").enable();
        mini.get("remove").enable();
        mini.get("cancel").enable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").enable();
        unmask();
    }


    if(action == 'edit') {//编辑
        edit_data = formSh.edit_data;
        //formCode = edit_data[0].formCode;
        console.log(edit_data,'edit_data');
    }else {
        edit_data = [];
    }

    //画按钮
    initBtn();
    //mask();
    
    //画组件
    var url =  ajaxUrl + "/formltems/findByFormListId.do";
    $.ajax({
        type : 'post',
        url : url,
        data : {
            formId : formId
        },
        dataType : 'json',
        success : function (data) {
            component_data = data['data'];
            console.log(component_data,'组件');
            for(var i=0;i<component_data.length;i++) {
                if(component_data[i].type == 'tab') {
                    arr_tab.push(component_data[i]);
                }
                if(component_data[i].type.indexOf('datepicker')>-1) {
                    datepick_main.push(component_data[i]);
                }
                if(component_data[i].cMath == "") {
                    component_data[i].cMath = JSON.stringify(component_data[i].cMath);
                }
                if(component_data[i].type.indexOf('buttonedit')>-1) {

                    var item = $.parseJSON(component_data[i].ref).ref.cTableField;//group_name
                    if(item == textField) {//保存参照的字段对应的组件name
                        refField = component_data[i].cTableField
                    }
                }
            }
            create_tab(arr_tab);
            showForm(component_data);//渲染
            //编辑赋值
            if(action == 'edit') {
            	  console.log(edit_data);
                  var formField = $("#formField").children();
                  console.log(formField,'formField');
                  for(var i = 0; i <formField.length; i++){
                      console.log(formField[i].id,'id');
                      if(formField[i].className == 'form_items') {//主表组件

                          var form = new mini.Form("#"+formField[i].id);
                          form.setData(edit_data[formSh.cTableName][0], false);
                          var index = formField[i].id.indexOf('buttonedit')
                       
                          if(index > -1) {
                        	  console.log(edit_data[formSh.cTableName][0]);
                        	  for(var item in edit_data[formSh.cTableName][0]) {
                        		  var setBE = edit_data[formSh.cTableName][0];
                        		  if(item == formField[i].children[1].children[1].name) {
                                	  mini.get("right"+formField[i].id).setText(setBE[item]);
                        		  }
                        	  }
                          }
                          edit_form = edit_data[formSh.cTableName][0];

                      }else {//表格
                    	  if(formField[i].className.indexOf('mini-menu') == -1) {

                    		  var grid = mini.get(formField[i].id.match(/dg(\S*)/)[1]);
                              grid.setData("");
                              var temp = formField[i].childNodes[2].className.split(' ');
                              var mtableName;
                              for(var m=0;m<temp.length;m++) {
                                  if(temp[m].indexOf('mtable-')>-1) {
                                      mtableName = temp[m].substring(temp[m].indexOf("-")+1);
                                  }
                              }
                              
                              // var e = edit_data[formField[i].id.substring(8)];
                              // for(var k = 0; k <e.length; k++) {
                              //     e[k].cTableName = formField[i].id.substring(8);//加入子表名
                              // }
                              if(edit_data[mtableName] == []){
                            	  grid.setData([{},{}]);
                              }else {
                                  grid.setData(edit_data[mtableName], false);
                              }                    
                              edit_table.push({
                                  cTableName: mtableName,
                                  obj: edit_data[mtableName]
                              });
                    	  }
                      }
                  }
                  unmask();
            }
            //新增档案赋值
            if(action == 'add' && menusFormTypes == 'complex') {
                console.log(textField,'textField');//参照的字段
                console.log(textFieldValue,'textFieldValue');

                var formField = $("#formField").children();
                for(var i = 0; i <formField.length; i++){
                    var fieldName = formField[i].children[1].children[1].name;//comp_name
                    console.log(fieldName,'fieldName');//需要赋值的组件name
                    if(formField[i].className == 'form_items') {//主表组件

                        var index = formField[i].id.indexOf('buttonedit');
                        if(fieldName == refField) {
                            if(index > -1) {
                                mini.get("right"+formField[i].id).setText(textFieldValue);
                                mini.get("right"+formField[i].id).setValue(textFieldValue);
                            }else {
                                mini.get("right"+formField[i].id).setValue(textFieldValue);

                            }
                        }

                    }else {//表格
                        if(formField[i].className.indexOf('mini-menu') == -1) {

                            // var grid = mini.get(formField[i].id.match(/dg(\S*)/)[1]);
                            // grid.setData("");
                            // var temp = formField[i].childNodes[2].className.split(' ');
                            // var mtableName;
                            // for(var m=0;m<temp.length;m++) {
                            //     if(temp[m].indexOf('mtable-')>-1) {
                            //         mtableName = temp[m].substring(temp[m].indexOf("-")+1);
                            //     }
                            // }
                            // if(edit_data[mtableName] == []){
                            //     grid.setData([{},{}]);
                            // }else {
                            //     grid.setData(edit_data[mtableName], false);
                            // }
                        }
                    }
                }
                unmask();
            }

            // localStorage.clear();
            // localStorage.removeItem("formShow");

        },
        error : function (message) {
            // console.log(message);
        }
    })

}


function initBtn() {

    $.ajax({
        type : 'post',
        url : ajaxUrl+"/buttons/findByState.do",
        //url : "http://192.168.31.65:8080/bpm/buttons/findByState.do",
        dataType : 'json',
        success : function (data) {
            console.log(data);
            for(var i=0;i<data.data.length;i++) {
                switch (data.data[i].buttonText) {
                    case '增加':
                        $("#add").css({display:"inline-block"});break;
                    case '修改':
                        $("#edit").css({display:"inline-block"});break;
                    case '删除':
                        $("#remove").css({display:"inline-block"});break;
                    case '取消':
                        $("#cancel").css({display:"inline-block"});break;
                    case '保存':
                        $("#save").css({display:"inline-block"});break;
                    case '参照':
                        $("#refer").css({display:"inline-block"});
                        $.ajax({
                            type : 'POST',
//                            url: "http://192.168.31.65:8080/bpm/referenceForm/referenceFormColumn.do?targerDocId="+formId,
                            url : ajaxUrl + "/referenceForm/referenceFormColumn.do?targerDocId="+formId,
                            dataType : 'json',
                            contentType : "application/json",
                            success : function(data) {
                                console.log(data);
                                var popupMenu = '';
                                if(data.data.length>0) {
                                    for(var i=0;i<data.data.length;i++) {
                                        popupMenu += "<li iconCls='icon-open' onclick='openRef("+data.data[i].formListId+")'>"+data.data[i].formName+"</li>\n";
                                    }
                                }else {
                                    popupMenu += "<li iconCls='icon-open'>暂无数据</li>\n";
                                }
                                $("#popupMenu").append(popupMenu);
                                mini.parse();
                            },
                            error : function(jqXHR, textStatus, errorThrown) {

                            }
                        })
                }

            }
        },
        error : function (message) {

        }
    })

}

//参照生单
function openRef(data) {
    mini.open({
        url : bootPATH + "../frame/frame1/pages/reference/selectFormReference.html",
        title : "选择参照",
        width: 850,
        height: 500,
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {       //如果点击“确定”
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'----');
                formRefData = data;
                var formField = $("#formField").children();
                console.log(formField,'formField');
                for(var i = 0; i <formField.length; i++){
                    console.log(formField[i].id,'id');
                    if(formField[i].className == 'form_items') {//主表组件

                        var form = new mini.Form("#"+formField[i].id);
                        form.setData(formRefData.rows1[0], false);
                        if(formField[i].id.indexOf('buttonedit'>-1)) {//参照赋值
                            for(var item in formRefData.rows1[0]) {
                                var setBE = formRefData.rows1[0];
                                if(item == formField[i].children[1].children[1].name) {
                                    mini.get("right"+formField[i].id).setText(setBE[item]);
                                }
                            }
                        }

                    }else {//表格
                        if(formField[i].className.indexOf('mini-menu') == -1) {

                            var grid = mini.get(formField[i].id.match(/dg(\S*)/)[1]);
//                            grid.setData("");
//                            var temp = formField[i].childNodes[2].className.split(' ');
                            if(formRefData.rows2 == []){

                            }else {
                                grid.addRows(formRefData.rows2);
                            }
                        }
                    }
                }
            }
        }
    })
}
//实例化组件
function showForm(data) {
    console.log(data);
    cFormName = data[0].cFormName;
    $("#formName").append("<h1>"+ cFormName +"</h1>");//表标题

    for(var i = 0; i < data.length; i++){

        var type = data[i].type;

        if(type.indexOf('tab_')>-1) {
            var id = data[i].tabs_id;
            var tabs = mini.get(id);
            var tabEl = tabs.getTabBodyEl(tabs.getTab(data[i].tab_id));
            var param = {
                area: "div[id='" + tabEl.id + "']",
                c_id: id,//整个页签
                tab_id: data[i].tab_id//插入的当前页签
            }
            create(type,data[i],"div[id='" + tabEl.id + "']");
        }else {
            create(type,data[i],'#formField');
        }
    }
    create_table(arr_table);
    create_table(arr_tab_table,'tab');
}

function create(type,data,area) {

    if (type.indexOf('textbox')>-1) { // 文本框
        create_base(data,area);

    } else if (type.indexOf('textarea')>-1) { // 文本域
        create_base(data,area);

    } else if (type.indexOf('formname')>-1) { // 文本
        create_txt(data,area);

    } else if (type.indexOf('spinner')>-1) { // 文本
        create_base(data,area);

    } else if (type.indexOf('datepicker')>-1) { //时间
        create_base(data,area);

    } else if (type.indexOf('combobox')>-1) {//下拉框
        create_base(data,area);

    } else if (type.indexOf('checkbox')>-1) {//复选框
        create_base(data,area);

    } else if (type.indexOf('buttonedit')>-1) {//参照
        create_base(data,area);

    } else if (type == 'table') {//表格
        arr_table.push(data);
        arr_cMath_child.push($.parseJSON(data.cMath).newStrEn);

    } else if (type == 'tab') {//页签
        // create_tab(data);
        // arr_tab.push(data);
    } else if (type == 'tab_table') {//tab表格
        arr_tab_table.push(data);
        arr_cMath_child.push($.parseJSON(data.cMath).newStrEn);

    }
}

function create_txt(data,area) {
    console.log(data,'data');
    if(data.cFontSize == '' || data.cFontSize == undefined) {
        data.cFontSize = 14;
    }
    var form_items = '<div id="'+ data.c_id + '" class="form_items" ' +
        'style="top:'+(data.iConY)+'px;left:'+data.iConX+'px;font-size:'+data.cFontSize+'px">'+
        data.cFormTitle+'</div>';

    $(area).append(form_items);
    $('#'+ data.c_id).css({
        width: data.iWidth + 5,
        height: data.iLabHeight,
        "font-size": 14
        // "margin-bottom": 4
    });
    mini.parse();
    
}

function create_base(data,area) {
	console.log(data,'data');
    var miniclass;
    if(area == '#formField') {
        miniclass = data.type;
    }else {
        miniclass = data.type.match(/tab_(\S*)/)[1];
    }
    if(miniclass.indexOf('checkbox')>-1) {
        miniclass = 'checkboxlist';
    }
    var form_items = '<div id="'+ data.c_id + '" class="form_items" ' +
        'style="top:'+(data.iConY)+'px;left:'+data.iConX+'px">' +
        '<label id="left'+ data.c_id + '">'+ data.cLadText + ':</label>\n' +
        '<input id="right'+ data.c_id +'" name="'+ data.cTableField +'"' +
        '   class="mini-'+miniclass+' visibility" ';

    //必填
    if(data.cNull == 'true') {
        form_items +=  ' required="true"';
    }else {
        form_items +=  ' required="false"';
    }
    //验证
    if(data.cRequire == 'none' || data.cRequire == '' || data.cRequire == undefined) {

    } else {
    	form_items +=  ' vtype="'+data.cRequire+'"';
    }
    if(data.type.indexOf('spinner')>-1) {
		 form_items +=  ' decimalPlaces="'+data.cSpinner+'" allowNull="'+!data.cNull+'" value="null" minValue="-10000000000" maxValue="10000000000" ';
	}
    form_items += ' /></div>';
    $(area).append(form_items);
    mini.parse();
    arr_cMath_main.push({math: $.parseJSON(data.cMath).newStrEn});
    arr_cMath_main[arr_cMath_main.length-1]['id'] = data.c_id;

    // console.log(data.type,$('#'+ data.c_id).css('marginTop'));
    $('#'+ data.c_id).css({
        width: data.iWidth + 5,
        height: data.iLabHeight,
        // "margin-bottom": 4
    });
    $('.form_items>span>span').css({
        height: '98%'
    });

    $('#left'+ data.c_id).css({
        width: data.iWidth - data.iLabWidth,
        height: data.iLabHeight,
        "text-align": "center",
        "font-size": data.cFontSize +'px',
        "vertical-align": "middle",
        "display": "inline"
    });
    $('#right'+ data.c_id).css({
        width: data.iLabWidth,
        height: data.iLabHeight
    });
    if(data.cFontSize != '' || data.cFontSize != undefined) {
        $('#'+data.c_id+'>span>span>input').css('cssText','font-size:'+ data.cFontSize +'px !important')
    }
    mini.parse();


    //主表公式
    var cMath = $.parseJSON(data.cMath).newStrEn;

    //主表 值改变时，更新其他公式结果
    mini.get('#right'+ data.c_id).on("valuechanged", function (e) {

        console.log(arr_cMath_main,'所有主表公式');
        // console.log(arr_cMath_child,'所有子表公式');
        console.log(data.c_id);

        //遍历所有主表公式
        for(var i=0;i<arr_cMath_main.length;i++) {
            var str = arr_cMath_main[i].math;
            if(str != '' && str != undefined) {
            	
                var param = setLinkage(e,arr_cMath_main[i].math,str,'base');
                str = param.str;
                var mathType = param.mathType;
                var linkId = param.linkId;//关联类型设置的id
                if(mathType == 'mathType_link') {//关联

                    	if(str.fileldValue != undefined){
                    		$.ajax({
                                type : 'POST',
                                url : ajaxUrl+'/dbsource/casacade.do ',
                                dataType : 'json',
                                data : str,
                                success: function (data) {
                                    mini.get('right'+linkId).setValue(data);
                                },
                                error: function (jqXHR, textStatus, errorThrown) {

                                }
                            })
                    }else {
                        mini.get('right'+linkId).setValue('');
                    }

                }else {//计算或拼接
                    var thisStr = str.split('=')[0];//可以赋值的字段
                    if(thisStr.indexOf(e.sender.name) == -1 ) {//不等于已填写的字段，则赋值
                        mini.get('#right'+ arr_cMath_main[i].id).setValue(evil(str));
                    }
                }
            }
        }
    });

    arr_main.cTableName = data.cTableName;
    arr_main.obj[data.cTableField] = "";


    //主表 个性化
    if(data.type.indexOf('datepicker')>-1) {//时间选择器
    	if(data.cFormat != '' || data.cFormat != undefined) {
    		 mini.get('right'+data.c_id).setFormat(data.cFormat);
    	}
    }else if(data.type.indexOf('spinner')>-1) {//数值

    }else if(data.type.indexOf('combobox')>-1) {//下拉框
        // console.log(data.cCombo);
        var combo_arr = data.cCombo.split(/[(\r\n)\r\n]+/);
        // console.log(combo_arr);

        var combo_data = [];
        for(var i=0;i<combo_arr.length;i++) {
            combo_data.push({
                'id':combo_arr[i],'text':combo_arr[i]
            })
        }
        mini.get('right'+data.c_id).setData(combo_data);

    }else if(data.type.indexOf('buttonedit')>-1) {//参照
        mini.get('right'+ data.c_id).on("buttonclick",function (e) {
        	var Ref = $.parseJSON(data.ref);
            mini.open({
                url : bootPATH + "../frame/frame1/pages/formDesign/selectRef.html",
                title : "请选择",
                onload: function () {       //弹出页面加载完成
                    var iframe = this.getIFrameEl();
                    var SetData = {};
                    if(data.cTableField == "parent_level") {//父级id
                        SetData = {ref: {formListId: formId},menuId: menuId};
                    } else if(data.cTableField == refField) {//重选参照的字段，更改complex_add_value的值
                        SetData = {ref: Ref.ref,menuId: menuId};
                        reSelectFlag = true;
                    }else {
                        SetData = {ref: Ref.ref,menuId: menuId};
                    }
                    iframe.contentWindow.SetData(SetData);
                },
                ondestroy: function (action) {  //弹出页面关闭前
                    if (action == "ok") {
                        var iframe = this.getIFrameEl();
                        var RefData = iframe.contentWindow.onTableOk();
                        RefData = mini.clone(RefData);
                        console.log(RefData,'selectRef');
                        // console.log(Ref.ref.cTableField);
                        // console.log(RefData[Ref.ref.cTableField]);
                        if(data.cTableField == "parent_level") {//父级id
                            mini.get('right'+ data.c_id).setText(RefData.id);
                            mini.get('right'+ data.c_id).setValue(RefData.id);
                            mini.get('right'+ data.c_id).doValueChanged();
                        }else {
                            mini.get('right'+ data.c_id).setText(RefData[Ref.ref.cTableField]);
                            mini.get('right'+ data.c_id).setValue(RefData[Ref.ref.cTableField]);
                            mini.get('right'+ data.c_id).doValueChanged();
                        }
                        if(reSelectFlag) {
                            complex_add_value = RefData.id;
                        }
                    }
                }
            })
        })
    }else {//文本类设置长度限制
        if(data.cLength != '') {
            mini.get('right'+data.c_id).setMaxLength(data.cLength);
        }

    }
}

function create_table(arr_table,area) {

    arr_table = jsonByGroup(arr_table);//表格按数据库表名分组
    console.log(arr_table,'arr_table分组后');
    for(var i = 0; i < arr_table.length; i++) {
        //arr_table[i]是一个表格
        var id = arr_table[i].c_id;
        var type = arr_table[i].type;
        var mTableName = arr_table[i].cTableName;
        var cols = JSON.parse(arr_table[i].gridColumns);
        var data = arr_table[i].data;
        // var grid = new mini.DataGrid();//js创建表格

        // var tree_data = [];
        for(var r=0;r<cols.length;r++) {

        	console.log(cols[r].columns);
            if(cols[r].columns == undefined) {//无分组
                // tree_data.push(cols[r]);
                cols[r] = setEditor(cols[r]);
            }else {
                var cols2 = cols[r].columns;
                for(var s=0;s<cols2.length;s++) {
                    if(cols2[s].columns == undefined) {//一层分组
                        // tree_data.push(cols2[s]);
                        cols2[s] = setEditor(cols2[s]);
                    }else {
                        var cols3 = cols2[s].columns;
                        for(var t=0;t<cols3.length;t++) {
                            // tree_data.push(cols3[t]);
                            cols3[t] = setEditor(cols3[t]);
                        }
                    }
                }
            }
        }
        console.log(cols,'整理分组');
        //个性化
        function setEditor(col) {

            if(col.editor.type == 'combobox') {//这一列是下拉框

                //设置下拉内容
                var combo_data = [];
                for(var k=0;k<data.length;k++) {
                    if(col.name == data[k].col_id) {
                        var combo_arr = data[k].cCombo.split(/[(\r\n)\r\n]+/);
                        combo_data = [];
                        for(var p=0;p<combo_arr.length;p++) {
                            combo_data.push({
                                'id':combo_arr[p],'text':combo_arr[p]
                            })
                        }
                    }
                }
                col.editor = {data:combo_data,type:col.editor.type};

            }else if(col.editor.type == 'datepicker') {

                if(type == 'tab_table') {
                    col.editor = {type:col.editor.type};
                }
                //格式化
                for(var k=0;k<data.length;k++) {
                    if(col.name == data[k].col_id) {
                        col.dateFormat = data[k].cFormat;
                        //默认设置当前日期
                        if(data[k].cDateDefault == 'true') {
                            datepick_child.push(data[k]);
                        }
                    }
                }
            }else if(col.editor.type == 'buttonedit') {

                if(type == 'tab_table') {
                    col.editor = {type:col.editor.type};
                }
                for(var k=0;k<data.length;k++) {
                    if(col.name == data[k].col_id) {
                        //弹窗
                        col.editor.onbuttonclick = "onSelectRef("+id+","+data[k].ref+")";
                    }
                }
            }else if(col.editor.type  == 'tab_table') {

                col.editor = {type:col.editor.type};

            }else {//文本类组件
                col.editor = {type:col.editor.type};
                //设置长度限制
                for(var k=0;k<data.length;k++) {
                    if(col.name == data[k].col_id && data[k].cLength != 0) {
                        col.editor.maxLength = data[k].cLength;
                    }
                }
            }
            //表格单元格验证
            for(var x=0;x<data.length;x++) {
                if(col.name == data[x].col_id) {
                    if(data[x].cNull == 'true') {//必填
                        if(data[x].cRequire == 'none') {//不验证
                            col.vtype="required";
                        }else {//验证
                            col.vtype="required;"+data[x].cRequire;
                        }
                    }else {//非必填
                        if(data[x].cRequire == 'none') {//不验证

                        }else {//验证
                            col.vtype=""+data[x].cRequire;
                        }
                    }
                }
            }
            return col;
        }
//         for(var j=0;j<cols.length;j++) {
//             if(cols[j].editor.type == 'combobox') {//这一列是下拉框
//
//                 //设置下拉内容
//                 var combo_data = [];
//                 for(var k=0;k<data.length;k++) {
//                     if(cols[j].name == data[k].col_id) {
//                         var combo_arr = data[k].cCombo.split(/[(\r\n)\r\n]+/);
//                         combo_data = [];
//                         for(var p=0;p<combo_arr.length;p++) {
//                             combo_data.push({
//                                 'id':combo_arr[p],'text':combo_arr[p]
//                             })
//                         }
//                     }
//                 }
//                 cols[j].editor = {data:combo_data,type:cols[j].editor.type};
//
//                 //                if(type == 'table') {
//                 //                	var editortype = cols[j].editor.type;
//                 //                	var editordata = cols[j].editor.data;
//                 //                	cols[j].editor = {type: editortype, data: editordata};
//                 ////                    cols[j].editor.data = cols[j].editor.data;
//                 //                }else {
//                 //                    for(var k=0;k<data.length;k++) {
//                 //                        if(cols[j].name == data[k].col_id) {
//                 //                            var combo_arr = data[k].cCombo.split(/[(\r\n)\r\n]+/);
//                 //                            var combo_data = [];
//                 //                            for(var p=0;p<combo_arr.length;p++) {
//                 //                                combo_data.push({
//                 //                                    'id':combo_arr[p],'text':combo_arr[p]
//                 //                                })
//                 //                            }
//                 //                        }
//                 //                    }
//                 //                    cols[j].editor = {data:combo_data,type:cols[j].editor.type};
//                 //                }
//
//             }else if(cols[j].editor.type == 'datepicker') {
//
//                 if(type == 'tab_table') {
//                     cols[j].editor = {type:cols[j].editor.type};
//                 }
//                 //格式化
//                 for(var k=0;k<data.length;k++) {
//                     if(cols[j].name == data[k].col_id) {
//                         cols[j].dateFormat = data[k].cFormat;
//                         //默认设置当前日期
//                          if(data[k].cDateDefault == 'true') {
//                               datepick_child.push(data[k]);
// //                            cols[j].defaultValue = new Date();
//                          }
//                     }
//                 }
//
//             }else if(cols[j].editor.type == 'buttonedit') {
//
//                 if(type == 'tab_table') {
//                     cols[j].editor = {type:cols[j].editor.type};
//                 }
//                 for(var k=0;k<data.length;k++) {
//                     if(cols[j].name == data[k].col_id) {
//                         //弹窗
//                         cols[j].editor.onbuttonclick = "onSelectRef("+id+","+data[k].ref+")";
//                     }
//                 }
//
//
//             }else if(cols[j].editor.type  == 'tab_table') {
//
//                 cols[j].editor = {type:cols[j].editor.type};
//
//             }else {//文本类组件
//
//                 cols[j].editor = {type:cols[j].editor.type};
//                 //设置长度限制
//                 for(var k=0;k<data.length;k++) {
//                     if(cols[j].name == data[k].col_id && data[k].cLength != 0) {
//                         cols[j].editor.maxLength = data[k].cLength;
//                     }
//                 }
//             }
//             //表格单元格验证
//             for(var x=0;x<data.length;x++) {
//                 if(cols[j].name == data[x].col_id) {
//                     if(data[x].cNull == 'true') {//必填
//                         if(data[x].cRequire == 'none') {//不验证
//                             cols[j].vtype="required";
//                         }else {//验证
//                             cols[j].vtype="required;"+data[x].cRequire;
//                         }
//                     }else {//非必填
//                         if(data[x].cRequire == 'none') {//不验证
//
//                         }else {//验证
//                             cols[j].vtype=""+data[x].cRequire;
//                         }
//                     }
//                 }
//             }
//         }
        var $clone = "    <div  id='dg"+id+"'>\n" +
            "        <div class='mini-toolbar' style='border-bottom:0;padding:0px;'>\n" +
            "            <table style='width:100%;'>\n" +
            "                <tr>\n" +
            "                    <td style='width:100%;'>\n" +
            "                        <a class='mini-button' iconCls='icon-add' onclick='onAddRow(e," + id + ")' plain='true'>新增行</a>\n" +
            "                        <a class='mini-button' iconCls='icon-remove' onclick='onRemoveRow(e," + id + ")' plain='true'>删除行</a>\n" +
            "                     </td>\n" +
            "                    \n" +
            "                </tr>\n" +
            "            </table>           \n" +
            "        </div>"

        $clone += "<div id='"+id+"' class='mini-datagrid mtable-"+mTableName+"' style=''\n>" +
            " contextMenu='#gridMenu" +id+ "'>\n" +
            "    <div property='columns'></div>\n" +
            "</div></div>";

        var gridMenu = "<ul id='gridMenu"+id+"' class='mini-contextmenu'  onbeforeopen='onBeforeOpenGrid(e," + id + ")'>\n" +
            "   <li name='add' iconCls='icon-add' onclick='onAddRow(e," + id + ")'>增行</li>\n" +
            "   <li name='remove' iconCls='icon-remove' onclick='onRemoveRow(e," + id + ")'>删行</li>\n" +
            "</ul>";


        if(area == 'tab') {
            var tabs = mini.get(data[i].tabs_id);
            var tabEl = tabs.getTabBodyEl(tabs.getTab(data[i].tab_id));
            var param = {
                area: "div[id='" + tabEl.id + "']",
                c_id: id,//整个页签
                tab_id: data[i].tab_id//插入的当前页签
            }
            // grid.render(document.getElementById(tabEl.id));

            var field = escapeJquery(tabEl.id);
            $("#"+field).append($clone);
            $("#"+field).append(gridMenu);

        }else {
            // grid.render(document.getElementById("formField"));

            $("#formField").append($clone);
            $("#formField").append(gridMenu);
        }
        mini.parse();
        var grid = mini.get(id);
        grid.set({
            url: "",
            columns: cols,
//            multiSelect:true,
            allowResize:false,
            allowCellEdit:true,
            allowCellSelect:true,
            cellEditAction: "celldblclick",
            allowRowSelect: true,
            showPager:false,
            editNextOnEnterKey:true,
            editNextRowCell:true,
            showModified: false,
            allowCellValid: true,
            
//            allowRowSelect:false,
//            enableHotTrack:false,
        });
        $("#dg"+id).css({
            width: arr_table[i].iWidth,
            height: arr_table[i].iLabHeight,
            "min-height": 100,
            top: arr_table[i].iConY,
            left: arr_table[i].iConX,
            position: "absolute"
        });
        $("#"+id).css({
            width: arr_table[i].iWidth,
            height: arr_table[i].iLabHeight,
            "min-height": 70
        });
        grid.setData([{},{}]);
        new CopyExcel(grid);        //Excel互操作插件
        mini.parse();
        addRow(id);//回车增加一行

        mini.get(id).on('cellbeginedit',function (e) {
            // console.log(e.sender);
            currentCell = e;
            // e.row['round'] = '123';

        });

        var cMath; //公式
        mini.get(id).on('drawCell',function (e) {
            // e.sender.id//表格id
            var data;
            for(var o=0;o<arr_table.length;o++) {
                if(arr_table[o].c_id == e.sender.id) {
                    data = arr_table[o].data;
                }
            }
            for(var p=0;p<data.length;p++) {
                if(data[p].cTableField == e.field){
                    cMath = $.parseJSON(data[p].cMath).newStrEn;
                }
            }

            console.log(cMath,'公式');
            var str = cMath;
            if(cMath != '' && cMath != undefined) {

            	var param = setLinkage(e,cMath,str,'table');
                str = param.str;
                var mathType = param.mathType;
                var linkType = param.linkType;
                var linkId = param.linkId;//关联类型设置的id
                var grid = mini.get(e.sender.id);
                if(mathType == 'mathType_other') {//计算/拼接
                    var thisStr = str.split('=')[0];
                    if(currentCell != undefined) {
                        if(thisStr.indexOf(currentCell.field) == -1 || linkType.indexOf('base') >-1) {
                            var result = evil(str);
                            console.log(result);
                            console.log(!isNaN(result));

                            if( result!=undefined && result!='$') {
                                e.cellHtml = result;
                                e.row[e.field] = result;
                    
                                // var curCell =mini.get(id).getCurrentCell();
                                // var rowData = {};
                                // rowData[curCell[1].field] = curCell[0][curCell[1].field];
                                // mini.get(id).updateRow(e.row, rowData);
                                // console.log(mini.get(id).getCurrentCell());
                                // var curCell =mini.get(id).getCurrentCell();
                                // e.row[curCell[1].field] = curCell[0][curCell[1].field];
                            }
                        }
                    }
                }else if(mathType == 'mathType_link') {//关联
                	if(str.fileldValue != undefined){
                		$.ajax({
                            type : 'POST',
                            url : ajaxUrl+'/dbsource/casacade.do ',
                            dataType : 'json',
//                            contentType: "application/json",
                            data : str,
                            success: function (data) {
//                            	e.cellHtml = data.data;
//                                e.row[e.field] = data.data;
                            	var up = {};
                            	up[e.field] = 'cs';
                            	mini.get(e.sender.id).updateRow(e.row, up);
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
//                                alert('失败！');
                            }
                        })//ajax
                	}
                }
            }
        })

        // mini.get(id).on("cellendedit", function (e) {
        //     console.log(e);
        //     console.log(e.column,'所在列');
        //     console.log(e.field,'列字段');
        //     console.log(e.row,'行数据');
        //     console.log(data[0].c_id,'表格id');
        //     for(var p=0;p<data.length;p++) {
        //         if(data[p].cTableField == e.field){
        //             cMath = $.parseJSON(data[p].cMath).newStrEn;
        //         }
        //     }
        //
        //     console.log(cMath,'公式');
        //     var str = cMath;
        //     if(cMath != '' && cMath != undefined) {
        //         // $.each(cMath.match(/[^\[]+(?=\])/g), function(i, word) {
        //         //     console.log(i, word);
        //         //     var value;
        //         //     if(i>0) {//等式右侧
        //         //         for(var i=0;i<component_data.length;i++) {
        //         //             if(component_data[i].cTableField == word) {
        //         //
        //         //                 if(component_data[i].type == 'table') {//变量是表格类型
        //         //                     var mathCol_data = mini.get(component_data[i].c_id).getData();
        //         //                     console.log(mathCol_data);
        //         //                     for(var n=0;n<mathCol_data.length;n++) {
        //         //                         if(mathCol_data[n][word] != undefined && mathCol_data[n]._id==e.row._id) {
        //         //                             value = mathCol_data[n][word];
        //         //                         }
        //         //                     }
        //         //
        //         //                 }else {
        //         //                     value = mini.get('right'+component_data[i].c_id).getValue();
        //         //                 }
        //         //                 var pattern = '\\['+word+'\\]';
        //         //                 str = str.replace(new RegExp(pattern,'g'),value);
        //         //             }
        //         //         }
        //         //     }
        //         // });
        //         // console.log(str,'str');
        //         str = setLinkage(e,cMath,str);
        //         console.log(evil(str));
        //         var row = {};
        //         row[e.field] = evil(str);
        //         console.log(e.row,'e.row');
        //         console.log(row,'更新row');
        //         // console.log(mini.get(id).getSelected())
        //         // console.log(mini.get(id).getRowByUid(row._uid))
        //         console.log(mini.get(id).getCurrentCell());
        //
        //         // mini.get(id).cancelEdit();
        //         // mini.get(id).cancelEditRow(e.row);
        //         // mini.get(id).updateRow(e.row, {orderLimeted_child:'000',orderType_child:'888'});//here
        //         if(evil(str) == '$') {
        //
        //         }else {
        //             mini.get(id).updateRow(e.row, row);//here
        //         }
        //     }
        // });

    }//每个arr[i]是一个表格
}

function create_tab(arr_tab) {

    arr_tab = jsonByGroup(arr_tab);//表格按数据库表名分组
    console.log(arr_tab,'arr_tab分组后');
    for(var i = 0; i < arr_tab.length; i++) {
        //arr_table[i]是一个表格
        var id = arr_tab[i].c_id;
        var data = arr_tab[i].data;
        var div = '';
        for(var j=data.length-1;j>=0;j--) {
            div = "<div name='"+data[j].tab_id+"' title='"+data[j].cTabText+"'> </div>\n"+div;
        }

        var $clone = "<div id='"+id+"'class='mini-tabs' activeIndex='0'>\n"+div+"</div>";
        $('#formField').append($clone);
        mini.parse();
        $("#"+id).css({
            width: data[0].iWidth,
            height: data[0].iLabHeight,
            "min-height": 100,
            top: data[0].iConY,
            left: data[0].iConX,
            position: "absolute"
        });
    }



}

//删除表格行
function onRemove(e,id) {
    var grid = mini.get(id);
    var row = grid.getSelected();
    if (row) {
        alert("删除：" + row.loginname)
    }
}

//对象数组分组
function jsonByGroup(arr) {
    console.log(arr);
    var map = {},
        dest = [];
    for(var i = 0; i < arr.length; i++){
        var ai = arr[i];
        if(!map[ai.c_id]){
            dest.push({
                // cTableName: ai.cTableName,
                c_id: ai.c_id,
                cFormName: cFormName,
                cTableName: ai.cTableName,
                type: ai.type,
                data: [ai],
                gridColumns: ai.gridColumns,
                iConX: ai.iConX,
                iConY: ai.iConY,
                iLabHeight: ai.iLabHeight,
                iLabWidth: ai.iLabWidth,
                iWidth: ai.iWidth
            });
            map[ai.c_id] = ai;
        }else{
            for(var j = 0; j < dest.length; j++){
                var dj = dest[j];
                if(dj.c_id == ai.c_id){
                    dj.data.push(ai);
                    break;
                }
            }
        }
    }

    // console.log(dest,'分组后');
    return dest;
}

//jq id含有特殊字符的转义
function escapeJquery(srcString) {
    // 转义之后的结果
    var escapseResult = srcString;

    // javascript正则表达式中的特殊字符
    var jsSpecialChars = ["\\", "^", "$", "*", "?", ".", "+", "(", ")", "[",
        "]", "|", "{", "}"];

    // jquery中的特殊字符,不是正则表达式中的特殊字符
    var jquerySpecialChars = ["~", "`", "@", "#", "%", "&", "=", "'", "\"",
        ":", ";", "<", ">", ",", "/"];

    for (var i = 0; i < jsSpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp("\\"
            + jsSpecialChars[i], "g"), "\\"
            + jsSpecialChars[i]);
    }

    for (var i = 0; i < jquerySpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i],
            "g"), "\\" + jquerySpecialChars[i]);
    }

    return escapseResult;
}

//字符串转换成公式
function evil(str) {
    var contactFlag = false;//赋值等式
    if(str.indexOf('=') == -1) {//不是等式
        str = '';
    }else {
        str = str.substring(str.indexOf("=")+1);//提取等号右侧

        // //赋值等式
        // var count = str.split('[').length -1;//单词出现的次数
        // console.log(str.indexOf('[') == 0)
        // console.log(str.indexOf(']') == str.length-1)
        // console.log(count == 1)
        // if(str.indexOf('[') == 0 && str.indexOf(']') == str.length-1 && count == 1) {
        //     contactFlag = true;
        // }
    }

    console.log(str,'公式');
    if(str.indexOf('undefined') == -1) {//不含undefined字段
        console.log(str.indexOf('拼接'));
        if(str.indexOf('拼接') == -1) {//加减运算
            str = str.replace(new RegExp('×','g'),'*');
            str = str.replace(new RegExp('÷','g'),'/');
            console.log(new Function('return ' + str)(),'计算结果');
            return new Function('return ' + str)();
        }else {//拼接
            str = str.replace(new RegExp('拼接','g'),'');
            console.log(str);
            return str;
        }

    }else {
        return '$';
    }

}
//设置公式联动
function setLinkage(e,cMath,str,type) {
    //cMath：公式,str：可处理的公式
    var value;
    var linkType;//base类型，table类型，base+table类型
    var mathType;//联动，计算/拼接
    if(cMath.indexOf('关联')>-1) {//关联
        mathType = 'mathType_link';
        var a;var b;var c;var d;var linkId;var fileldValue;
        $.each(cMath.match(/[^\[]+(?=\])/g), function(j, word){
            if(j == 0) a = word;//须填写的字段
            if(j == 1) b = word;//关联的字段
        })
        for(var i=0;i<component_data.length;i++) {
            if(component_data[i].cTableField == a) {
                d = component_data[i].cTableName;
                linkId = component_data[i].c_id;
            }
        }
        if(type == 'table') {//子表之间关联
        	fileldValue = e.row[b];
        }else if(type == 'base') {//主表之间关联
        	fileldValue = e.value;
        }
        var link = {
                fileld: b,
                fileldValue: fileldValue,
                returnFileld: a,
                cTableName: d
        }; 
        return {str: link, linkType: linkType, mathType: mathType, linkId:linkId};

    }else {//计算/拼接
        mathType = 'mathType_other';
        $.each(cMath.match(/[^\[]+(?=\])/g), function(i, word) {//提取[]中的字段
            console.log(i, word);
            if(i>0) {//等式右侧的字段
                for(var i=0;i<component_data.length;i++) {
                    if(component_data[i].cTableField == word) {
                        if(component_data[i].type == 'table' || component_data[i].type == 'tab_table') {//变量是表格类型
                            value = e.record[word];
                            if(type == 'table' || type == 'tab_table') {
                                linkType+= 'table,';
                            }
                        }else {
                            value = mini.get('right'+component_data[i].c_id).getValue();
                            linkType+= 'base,'
                        }
                        var pattern = '\\['+word+'\\]';
                        str = str.replace(new RegExp(pattern,'g'),value);//字段替换成值
                    }
                }
            }
        });
        return {str: str, linkType: linkType, mathType: mathType, linkId:linkId};
    }
}

//表格回车时添加一行
function addRow(id) {
    var grid = mini.get(id);
    grid.on("celleditenter", function (e) {
        // console.log(grid,'回车事件');
        var index = grid.indexOf(e.record);
        if (index == grid.getData().length - 1) {
            var row = {};
            grid.addRow(row);
        }
    });
}

//表格选择参照
function onSelectRef(e,Refer) {

    console.log(Refer,'Refer table');
    var Ref = Refer;
//    var Ref = $.parseJSON(Refer.ref);
    mini.open({
        url : bootPATH + "../frame/frame1/pages/formDesign/selectRef.html",
        title : "选择",
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = {ref: Ref.ref,menuId: menuId};
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var RefData = iframe.contentWindow.onTableOk();
                RefData = mini.clone(RefData);
                console.log(RefData,'selectRef');

                //设置弹窗选择后的值
                var grid = mini.get(e.id);
                grid.cancelEdit();
                var row = grid.getSelected();
                console.log(row,'row');
                var curCell = grid.getCurrentCell();
                var field = curCell[1].field;
                console.log(field,'field');//当前单元格
                var updateData = {};
                console.log(Ref.ref.cTableField);
                console.log(RefData[Ref.ref.cTableField]);
                updateData[field] = RefData[Ref.ref.cTableField];
//              updateData[field] = RefData["orderPeople"];
                grid.updateRow(row, updateData);
            }
        }
    })
}

//表单操作
function getForm() {
    var form = new mini.Form("#formField");
    var data = form.getData();
    console.log(data);
    return data;
}
function setForm(obj) {
    var form = new mini.Form("#formField");
    form.setData(obj, false);
}
function resetForm() {
    var form = new mini.Form("#formField");
    form.reset();
}
function clearForm() {
    var form = new mini.Form("#formField");
    form.clear();
}
function clearTable() {
    console.log(component_data);
    for(var i=0;i<component_data.length;i++) {
    	if(component_data[i].type.indexOf('table')>-1) {
    		mini.get(component_data[i].c_id).setData([{},{}]);
    	}
    }
}

//表格--右键菜单
function onBeforeOpenGrid(e,id) {
    var grid = mini.get(id);
    var menu = e.sender;

    var row = grid.getSelected();
    // var rowIndex = grid.indexOf(row);
    if (!row) {
        e.cancel = true;
        e.htmlEvent.preventDefault();//阻止浏览器默认右键菜单
        return;
    }
}

function actions(act) {
    if(act == 'add'){
        save_data = [];
    	formCode = new Date().getTime();
        mini.get("add").disable();
        mini.get("edit").disable();
        mini.get("save").enable();
        mini.get("remove").enable();
        mini.get("cancel").enable();
        mini.get("approve").enable();
        mini.get("abandon").enable();
        mini.get("refer").enable();
        unmask();
        clearForm();
        clearTable();
        //设置主表当前日期
        for(var i=0;i<datepick_main.length;i++) {
	         if(datepick_main[i].cDateDefault == 'true') {
	             mini.get('right'+datepick_main[i].c_id).setValue(new Date());
	         }
        }
        //设置表格默认日期
        //datepick_child的数据是否默认都为true        
        
        for(var i=0;i<datepick_child.length;i++) {
        	var grid = mini.get(datepick_child[i].c_id);
        	var rows = grid.getData()//获取所有行
	        for(var j=0;j<rows.length;j++) {
	        	var up = {};
	        	up[datepick_child[i].cTableField] = new Date();
	        	grid.updateRow(rows[j], up);
	        }
        }
    }else if(act == 'edit') {
    	mini.get("add").disable();
        mini.get("edit").disable();
        mini.get("save").enable();
        mini.get("remove").enable();
        mini.get("cancel").enable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").enable();

        unmask();
    }else if(act == 'save') {
    	save();
    }else if(act == 'remove') {
        if(save_data.length != 0) {
            removeForm();
            function removeForm() {
                var del_data = [];
                for(var i=0;i<save_data.length;i++) {
                    del_data.push({
                        cTableName: save_data[i].cTableName,
                        mTableId: save_data[0].id,
                        formId: formId
                    })
                }
                del_data = reduce(del_data,'cTableName');//arr:去重的数组，type：去重的参照索引
                console.log(del_data,'删除的数据');

                $.ajax({
                    url: ajaxUrl + "/formltems/deleteFormSource.do",
                    type: "post",
                    dataType: "json",
                    traditional: true,
                    data: {
                        obj: JSON.stringify(del_data)
                    },
                    success: function(data){
                        console.log(data,'数据');
                        mini.showTips({
                            content: "删除成功",
                            state: 'success',
                            x: 'Center',
                            y: 'Top',
                            timeout: 2000
                        });
                        clearForm();
                        clearTable()
                        mask();

                    	mini.get("add").enable();
                        mini.get("edit").disable();
                        mini.get("save").disable();
                        mini.get("remove").disable();
                        mini.get("cancel").disable();
                        mini.get("approve").disable();
                        mini.get("abandon").disable();
                        mini.get("refer").enable();
                    },
                    error : function(data){
                        mini.alert('删除失败')
                    }
                });
            }
        }else {
//            mini.alert('表单尚未保存!');
        }
    }else if(act == 'cancel') {

        mini.get("add").enable();
        mini.get("edit").disable();
        mini.get("save").disable();
        mini.get("remove").disable();
        mini.get("cancel").disable();
        mini.get("approve").disable();
        mini.get("abandon").disable();
        mini.get("refer").disable();
        mask();

    }else if(act == 'refer') {//参照

    }else if(act == 'submission'){
    	console.log(submission);
    	
    }
}

//设置遮罩
function mask() {
    mini.mask({
        el: document.getElementById('formField'),
    	html : "<div></div>",
//		cls : "mini-mask-loading",
		style : "height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
    });
}
//取消遮罩
function unmask() {
	mini.unmask(document.getElementById('formField'));
}

//表格增行
function onAddRow(e,id) {
    var newRow = { name: "New Row" };
    var grid = mini.get(id);
    grid.addRow(newRow);
    // grid.beginEditCell(newRow, "LoginName");
}
//表格删行
function onRemoveRow(e,id) {
    var grid = mini.get(id);
    var cTableName;
    for(var k=0;k<arr_table.length;k++) {
    	if(arr_table[k].c_id == id.id){
    		cTableName = arr_table[k].cTableName;
    	}
    }
    var rows = grid.getSelecteds();
    var data = grid.getData();
    if (rows.length > 0 && data.length > 1) {
        grid.removeRows(rows, true);
        console.log(rows,'del rows');
        var del_data = [];
        for(var i=0;i<rows.length;i++) {
            if(rows[i]._state != 'added') {
                del_data.push({
                    id: rows[i].id,
                    cTableName: cTableName
                });
            }
        }
        console.log(del_data,'del_data');
    
        $.ajax({
		    type : 'post',
		    url : ajaxUrl + '/dbsource/dbDelete.do',
		    data : JSON.stringify(del_data),
		    dataType : 'json',
            contentType: 'application/json',
		    success : function (data) {
		    	console.log(data);
		    },
		    error : function (message) {
		        // console.log(message);
		    }
		})
    }
}


//保存
var grid_datas= [];
function save(){
    arr_table = jsonByGroup(arr_table);//表格按数据库表名分组

    //表单验证
    var form = new mini.Form("#formField");
    form.validate();
    if (form.isValid() == false) return;
    //单元格验证
    for(var p=0;p<arr_table.length;p++) {
        var grid = mini.get(arr_table[p].c_id);
        grid.validate();
        if (grid.isValid() == false) {
            //alert("请校验输入单元格内容");
            var error = grid.getCellErrors()[0];
            grid.beginEditCell(error.record, error.column);
            return;
        }
    }

    //提交数据
    arr_child = [];
    grid_datas= [];
    var grid_datas_id= [];
    console.log(arr_main,'arr_main保存前');
    console.log(arr_table,'arr_table');
    console.log(arr_tab_table,'arr_tab_table');
    var child = [];//合并子表数据
    child = arr_table.concat(arr_tab_table);
    var form_data = getForm();
	
    for(item in form_data){
        console.log(form_data[item]);
//        console.log(new Date(form_data[item]));
//        console.log(new Date(form_data[item]).toString());
//	   	if(new Date(form_data[item]).toString().indexOf('中国标准时间')>-1) {
//	   		form_data[item] = standardToDate(form_data[item],'-');
//	   		console.log(form_data[item]);
//	   	}
        for(i in arr_main.obj){
            if(i == item) {
                arr_main.obj[i] = form_data[item];
            }
        }
    }
    var time = new Date().getTime();
    arr_main.obj.id = time;
    console.log(arr_main,'arr_main保存后');

    for(var i = 0;i<child.length;i++) {
        //每个arr[i]是一个表格
        var id = child[i].c_id;
        var cols = child[i].gridColumns;
        var data = child[i].data;
        var grid_data = mini.get(id).getData();

        if(grid_datas_id.indexOf(id) == -1) {
            grid_datas_id.push(id);
            grid_datas.push({
                id: id,
                data: grid_data
            });

            for(var j = 0;j<grid_data.length;j++) {
                // delete grid_data[j]._id;
                // delete grid_data[j]._uid;
                 delete grid_data[j]._state;
                arr_child.push({
                    cTableName: child[i].cTableName,
                    obj: grid_data[j]
                });
                arr_child[j].obj.id = new Date().getTime() + j*100;
                arr_child[j].obj.mTableId = time;
            }
        }
    }

    console.log(grid_datas,'grid_datas');
    console.log(arr_child,'arr_child保存后');
    // console.log(grid_datas,'grid_datas');

    //合并
    var arr_save = [];
    arr_save[0] = arr_main;
    arr_save[0].grid_data = JSON.stringify(grid_datas);
    arr_save[0].cFormName = cFormName;


    for(var i = 0;i<arr_child.length;i++) {

        arr_save.push(arr_child[i]);
    }
    console.log(arr_save,'保存的数据');

    var url;
    if(action == 'edit') {
        console.log(edit_form,'edit_form');
        console.log(edit_table,'edit_table');
        url = ajaxUrl + "/formltems/formDbSource.do";
        for(var i=0;i< arr_save.length;i++) {
            if(i == 0) {
                arr_save[i].obj.id = edit_form.id;
                arr_save[i].formId = formId;
                arr_save[i].formCode = formCode;
            }else {
                arr_save[i].obj.mTableId = edit_form.id;
                arr_save[i].mTableId = edit_form.id;
                arr_save[i].formId = formId;
            }
        }
    }else {
        url = ajaxUrl + "/dbsource/dbInsert.do";
    }

    for(var i=0;i< arr_save.length;i++) {
        arr_save[i].obj[complex_add_field] = complex_add_value;
    }
    save_data = arr_save;//全局
    arr_save = JSON.stringify(arr_save);
    console.log(arr_save);

//	url = "http://192.168.31.65:8080/bpm/dbsource/dbInsert.do";
    $.ajax({
        type : 'post',
        url : url,
        dataType : 'json',
        data : arr_save,
        contentType: 'application/json',
        success : function (data) {
            console.log(data);
            mini.showTips({
                content: "保存成功",
                state: 'success',
                x: 'Center',
                y: 'Top',
                timeout: 3000
            });
            mini.get("add").enable();
            mini.get("edit").enable();
            mini.get("save").disable();
            mini.get("remove").enable();
            mini.get("cancel").disable();
            mini.get("approve").enable();
            mini.get("abandon").enable();
            mini.get("refer").disable();
            mask();
            // console.log(t_arr,'表格id');
            // parent.removeTab();//保存成功，关闭页面
        },
        error : function () {
            mini.alert('保存失败');
        }
    })
}

function reduce(arr,type) {
    var hash = {};
    arr = arr.reduce(function(item, next) {
        hash[next[type]] ? '' : hash[next[type]] = true && item.push(next);
        return item
    }, [])
    // console.log(arr,'属性数组');
    return arr;
}

//时间戳转为日期格式
function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    return Y+M+D+h+m+s;
}
//中国标准时间转为日期格式
function standardToDate(date,type) {//中国标准时间转为时间格式
	var d = new Date(date);
//	d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(); 
	return d.getFullYear() + type + (d.getMonth() + 1) + type + d.getDate();
}
